package web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entity.Level;
import entity.Risk;
import entity.Role;
import entity.User;
import service.RiskService;
import service.UserService;

/**
 * Servlet implementation class CommitterServlet
 */
public class CommitterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String committerPath="/view/html/committer.jsp";
	private RiskService riskService;
	private UserService userService;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CommitterServlet() {
        super();
        riskService=new RiskService();
        userService=new UserService();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession(false);
		if(session.getAttribute("user")==null||((User)session.getAttribute("user")).getRole()==Role.RiskTracer){
			response.sendRedirect(request.getContextPath() + "/login");
			return;
		}
		
		session.setAttribute("tracers", userService.getAllTracer());
		request.getRequestDispatcher(committerPath).forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession(false);
		if(session.getAttribute("user")==null||((User)session.getAttribute("user")).getRole()==Role.RiskTracer){
			response.sendRedirect(request.getContextPath() + "/login");
		}
		if(request.getParameter("title")==null||"".equals((String)request.getParameter("title"))||request.getParameter("tracer")==null){
			request.setAttribute("error", "Please fill the form.");
			request.getRequestDispatcher(committerPath).forward(request, response);
			return;
		}
		User user=(User)session.getAttribute("user");
		Risk risk=new Risk();
		risk.setTitle((String)request.getParameter("title"));
		risk.setCommittedBy(user.getId());
		risk.setInfluence(Level.stringToLevel((String)request.getParameter("influence")));
		risk.setPossibility(Level.stringToLevel((String)request.getParameter("possibility")));
		risk.setTracer(Integer.parseInt((String)request.getParameter("tracer")));
		riskService.createRisk(risk);
		request.setAttribute("success", "Create a risk successfully!");
		request.getRequestDispatcher(committerPath).forward(request, response);
	}

}
